import axios from 'axios'

const FETCHED = 'FETCHED'
const FETCHING = 'FETCHING'
const ERROR = 'ERROR'
const init = {
    load:false,
    data:[],
    pagination:{
        total:0,
        showSizeChanger:true,
        showQuickJumper:true
    }
}

export function table(state=init, action) {
    switch(action.type) {
        case FETCHED:
            return {...state, data:action.data, load:false, pagination:{total:action.total}}
        case FETCHING:
            return {...state, load:true}
        case ERROR:
            return {...state, error:action.error, load:false}
        default:
            return state
    }
}

function fetching() {
    return {
        type:FETCHING
    }
}

function fetched(data, total) {
    return {
        type:FETCHED,
        data,
        total
    }
}

function error(error) {
    return {
        type:ERROR,
        error
    }
}

export function fetch(params={}) {
    return dispatch=>{
        dispatch(fetching())
        axios.get('/site/list', {'params':params}).then(res=>{
            if(res.status == 200) {
                const data = res.data
                if(data.code == 1) {
                    const result = data.data.data
                    const newresult = result.map(v=>{ return {...v, key:v.id}})
                    dispatch(fetched(newresult, Number(data.data.total)))
                } else {
                    dispatch(error(data.msg))
                }
            } else {
                dispatch(error('请求失败'))
            }
        })
    }
}